<script setup lang="ts">
import { ElButton, ElTree } from 'element-plus'
import type {
  EnergyBindItem,
  EnergyInfo,
  TableColumn,
} from '@/types'
import { energyApi } from '@/api'

// ------------------use------------------
// #region
const { $notify, $router } = useCurrentInstance()
const { vLoading, withLoading, loading }
  = useDefineLoading()
const [treeData, setTreeData] = useState<EnergyInfo[]>([])
const [bindInfoList, setBindInfoList] = useState<
  EnergyBindItem[]
>([])
// #endregion
// ------------------静态变量------------------
// #region
const columns: TableColumn<EnergyBindItem>[] = [
  {
    key: uuid(),
    type: 'index',
    width: '80',
    label: '序号',
  },
  {
    key: uuid(),
    label: '能源名称',
    prop: 'name',
  },
  {
    key: uuid(),
    label: '能源代码',
    prop: 'code',
  },
  {
    key: uuid(),
    label: '能源单位',
    prop: 'energyUnit',
  },
  {
    key: uuid(),
    label: '折标系数',
    prop: 'discountFactor',
  },
  {
    key: uuid(),
    label: '最新价格',
    prop: 'energyPrice',
  },
]
// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()
// #endregion
// ------------------reactive------
// #region

// #endregion
// ------------------computed------
// #region
// const computedEnergy = computed(() => {
//   return treeData.value.filter(item =>
//     computedBindIds.value.includes(item.id)
//   );
// });
const computedBindIds = computed(() =>
  bindInfoList.value.map(item => item.energyId),
)
// #endregion
// ------------------生命周期------------------
// #region
onMounted(() => {
  getTreeData()
  getBindIds()
})
// #endregion
// ------------------内置方法---------------------
// #region
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
// #endregion
// ------------------方法---------------------
// #region
async function getTreeData() {
  const { data: res } = await withLoading(
    energyApi.queryList,
  )()
  setTreeData(res)
}
async function getBindIds() {
  const { data: res } = await withLoading(
    energyApi.queryEnterpriseBindList,
  )()
  setBindInfoList(res)
  await nextTick()
  treeRef.value?.setCheckedKeys(computedBindIds.value)
}
async function bindEnterprise() {
  const ids = treeRef.value?.getCheckedKeys()
  if (!ids)
    return
  await energyApi.batchEnterprise(ids as number[])
  getBindIds()
  const func = $notify({
    title: '保存成功！',
    message: h(
      'div',
      {
        class: 'flex align-center',
      },
      [
        '在价格管理页面进行编辑！',
        // h(
        //   ElButton,
        //   {
        //     link: true,
        //     type: 'primary',
        //     onClick: goTo,
        //   },
        //   {
        //     default: () => '跳转',
        //   },
        // ),
      ],
    ),
    type: 'success',
  })
  async function goTo() {
    $router.push('/price-management')
    await nextTick()
    func?.close?.()
  }
}
function filterNode(value: string, data: EnergyInfo) {
  if (!value)
    return true
  return data.name.includes(value)
}
// #endregion
</script>

<template>
  <div class="align-center flex gap-sm">
    <div
      v-loading="{
        space: 'tree',
      }"
      class="panel height-fill padding-sm flex-incompressible flex-direction box-border flex gap-xs"
    >
      <div
        class="panel-header flex-incompressible align-center width-fill flex justify-between"
      >
        <h5 class="!margin-0">
          能源类别
        </h5>
        <ElButton
          type="primary"
          link
          @click="bindEnterprise"
        >
          保存
        </ElButton>
      </div>
      <el-input
        v-model="filterText"
        class="width-fill flex-incompressible"
      />

      <b-scrollbar class="flex-fillRemaining">
        <ElTree
          ref="treeRef"
          :data="treeData"
          default-expand-all
          show-checkbox
          node-key="id"
          :props="{
            children: 'children',
            label: 'name',
          }"
          :filter-node-method="filterNode as any"
        />
      </b-scrollbar>
    </div>
    <div class="flex-fillRemaining height-fill overflow">
      <view-table
        :loading="loading"
        :show-toolbox="false"
        :columns="columns"
        :data="bindInfoList"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
//-------------样式穿透-------------
</style>
